<?php

namespace app\common\service\driver;

use think\Exception;

/**
 * 腾讯云COS存储驱动
 */
class TencentCOSDriver
{
    protected $config;
    protected $cosClient;

    public function __construct($config)
    {
        $this->config = $config;
        $this->initCOSClient();
    }

    /**
     * 初始化COS客户端
     */
    protected function initCOSClient()
    {
        $configData = $this->config->config;
        
        if (empty($configData['secret_id']) || empty($configData['secret_key'])) {
            throw new Exception('腾讯云COS配置不完整：缺少SecretId或SecretKey');
        }
        
        if (empty($configData['region']) || empty($configData['bucket'])) {
            throw new Exception('腾讯云COS配置不完整：缺少Region或Bucket');
        }
        
        // 这里需要引入腾讯云COS SDK
        // 实际使用时需要安装：composer require qcloud/cos-sdk-v5
        try {
            $this->cosClient = new \Qcloud\Cos\Client([
                'region' => $configData['region'],
                'credentials' => [
                    'secretId' => $configData['secret_id'],
                    'secretKey' => $configData['secret_key'],
                ],
            ]);
        } catch (\Exception $e) {
            throw new Exception('腾讯云COS连接失败：' . $e->getMessage());
        }
    }

    /**
     * 上传文件
     */
    public function upload($file, $fileInfo)
    {
        $configData = $this->config->config;
        $bucket = $configData['bucket'];
        $key = $fileInfo['file_path'];
        
        try {
            $result = $this->cosClient->putObject([
                'Bucket' => $bucket,
                'Key' => $key,
                'Body' => fopen($file->getRealPath(), 'rb'),
            ]);
            
            // 生成访问URL
            $domain = $configData['domain'] ?? '';
            if ($domain) {
                $fileUrl = rtrim($domain, '/') . '/' . $key;
            } else {
                $fileUrl = $this->cosClient->getObjectUrl($bucket, $key);
            }
            
            return [
                'file_path' => $fileInfo['file_path'],
                'file_url' => $fileUrl
            ];
        } catch (\Exception $e) {
            throw new Exception('腾讯云COS上传失败：' . $e->getMessage());
        }
    }

    /**
     * 删除文件
     */
    public function delete($filePath)
    {
        $configData = $this->config->config;
        $bucket = $configData['bucket'];
        
        try {
            $this->cosClient->deleteObject(['Bucket' => $bucket, 'Key' => $filePath]);
            
            return true;
        } catch (\Exception $e) {
            throw new Exception('腾讯云COS删除失败：' . $e->getMessage());
        }
    }

    /**
     * 获取文件URL
     */
    public function getUrl($filePath)
    {
        $configData = $this->config->config;
        $domain = $configData['domain'] ?? '';
        
        if ($domain) {
            return rtrim($domain, '/') . '/' . $filePath;
        } else {
            // 生成访问URL
            return $this->cosClient->getObjectUrl($configData['bucket'], $filePath);
        }
    }

    /**
     * 检查文件是否存在
     */
    public function exists($filePath)
    {
        $configData = $this->config->config;
        $bucket = $configData['bucket'];
        
        try {
            $this->cosClient->headObject(['Bucket' => $bucket, 'Key' => $filePath]);
            
            return true;
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * 测试连接
     */
    public function test()
    {
        try {
            $this->cosClient->listObjects(['Bucket' => $this->config->config['bucket'], 'MaxKeys' => 1]);
            
            return true;
        } catch (\Exception $e) {
            throw new Exception('腾讯云COS连接测试失败：' . $e->getMessage());
        }
    }
}
